<template>
  <div class="category-list-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">分类管理</h1>
        </div>
        <el-button type="primary" @click="handleAdd" class="w-[100px]">
          添加分类
        </el-button>
      </div>
    </div>
    
    <!-- 分类列表卡片 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">分类列表</div>
          <div class="flex space-x-2">
            <el-button size="small" @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <!-- 分类表格 -->
        <el-table
          :data="categoryList"
          style="width: 100%"
          border
          row-key="id"
        >
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="分类名称" min-width="220" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="分类代码" width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="sortOrder" label="排序" width="100" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                size="small" 
                :type="scope.row.status === 1 ? 'success' : 'danger'"
              >
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="修改时间" min-width="180">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.updatedAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <el-button size="small" text @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button 
                size="small" 
                text 
                :type="scope.row.status === 1 ? 'warning' : 'success'" 
                @click="toggleStatus(scope.row)"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                size="small" 
                text 
                type="danger" 
                @click="deleteCategory(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { categoryAPI } from '~/services/api'

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

// 数据加载状态
const loading = ref(false)

// 分类列表数据
const categoryList = ref([])

const router = useRouter()
// 时间格式化
const formatDateTime = (val) => {
  if (!val) return '-'
  try {
    // 兼容后端 LocalDateTime 的 ISO 字符串
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return String(val)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return String(val)
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    loading.value = true
    
    // 调用后端API获取分类列表（该API直接返回数组数据）
    const result = await categoryAPI.getAllCategories()
    categoryList.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
    categoryList.value = []
  } finally {
    loading.value = false
  }
}

// 刷新数据
const handleRefresh = async () => {
  try {
    await loadCategories()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}



// 添加分类
const handleAdd = () => {
  router.push('/admin/category/add')
}

// 编辑分类
const handleEdit = (row) => {
  router.push(`/admin/category/edit/${row.id}`)
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const statusText = newStatus === 1 ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${statusText}「${row.name}」分类吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用后端API更新状态
    await categoryAPI.updateCategoryStatus(row.id, newStatus)
    
    // 更新本地数据
    row.status = newStatus
    
    ElMessage.success(`已${statusText}「${row.name}」分类`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态切换失败:', error)
      ElMessage.error('状态切换失败，请重试')
    }
  }
}

// 删除分类
const deleteCategory = async (id) => {
  try {
    const category = categoryList.value.find(item => item.id === id)
    
    await ElMessageBox.confirm(
      `确定要删除「${category?.name ?? ''}」分类吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用后端API删除分类
    await categoryAPI.deleteCategory(id)
    
    // 从本地列表中移除
    categoryList.value = categoryList.value.filter(item => item.id !== id)
    
    ElMessage.success(`已删除「${category?.name ?? ''}」分类`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}



// 初始化
onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
/* 表格样式优化 */
:deep(.el-table) {
  --el-table-header-bg-color: var(--el-fill-color-light) !important;
  --el-table-row-hover-bg-color: rgba(0, 0, 0, 0.02) !important;
  border-radius: 8px;
  overflow: hidden;
}


:deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}


/* 对话框样式 */
:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 15px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 15px;
}
</style>